<!-- pages/mine/change-phone/index.vue -->
<route lang="json5">
{
  style: {
    navigationBarTitleText: '修改手机号',
  },
}
</route>

<template>
  <view class="container">
    <view class="form-box">
      <view class="tip-text zh-tb-text">
        <text>更换手机号后，下次登录可使用新的手机号码</text>
      </view>

      <view class="current-phone zh-tb-text">
        <text>当前手机号：{{ maskPhone(currentPhone) }}</text>
      </view>

      <wd-form ref="formRef" :model="form" :rules="rules">
        <wd-cell-group>
          <wd-input
            label="新手机号"
            prop="newPhone"
            v-model="form.newPhone"
            placeholder="请输入新的手机号码"
            clearable
          />
        </wd-cell-group>
      </wd-form>

      <wd-button type="error" block class="mt-40" @click="handleSubmit">提交</wd-button>
    </view>

    <!-- 步骤2：验证验证码 -->
    <!-- <view v-else class="form-box">
      <view class="verify-tip">
        <text>验证码已发送至</text>
        <text class="phone">{{ maskPhone(form.newPhone) }}</text>
      </view>

      <wd-form ref="formRef" :model="form">
        <wd-cell-group>
          <wd-input
            label="验证码"
            label-width="50px"
            v-model="form.code"
            placeholder="请输入6位验证码"
          >
            <template #label>
              <view class="zh-tb-text">
                <text>新手机号</text>
              </view>
            </template>
</wd-input>
</wd-cell-group>
</wd-form>

<wd-button type="error" block class="mt-40" :loading="submitting" @click="handleSubmit">
  提交
</wd-button>
</view> -->
  </view>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useUserStore } from '@/store/user'
import { updatePhone } from '@/api/login'

const formRef = ref(null)
const userStore = useUserStore()
const showTibetan = import.meta.env.VITE_SHOW_TIBETAN === 'true'
const currentPhone = userStore.userInfo.phonenumber
const store = useUserStore()
const submitting = ref(false)

// 表单数据
const form = reactive({
  newPhone: '',
})

// 验证规则
const rules: any = {
  newPhone: [
    {
      required: true,
      message: '请输入新手机号',
    },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '手机号格式不正确',
    },
  ],
}

// 手机号脱敏显示
const maskPhone = (phone: string) => {
  return phone.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
}

// 提交修改
// const handleSubmit = async () => {
//   try {
//     if (!formRef.value) {
//       throw new Error('表单未初始化')
//     }

//     // 校验表单
//     const { valid, errors } = await formRef.value.validate()
//     if (!valid) {
//       console.log('表单校验未通过:', errors)
//       return
//     }
//     // step.value = 2
//     handleSendCode() // 自动发送验证码
//   } catch (error) {
//     console.log('表单验证失败', error)
//   }
// }

// 提交修改
const handleSubmit = async () => {
  // if (!form.code) {
  //   return uni.showToast({ title: '请输入验证码', icon: 'none' })
  // }

  // submitting.value = true
  try {
    if (!formRef.value) {
      throw new Error('表单未初始化')
    }
    // 校验表单
    const { valid, errors } = await formRef.value.validate()
    if (!valid) {
      console.log('表单校验未通过:', errors)
      return // ✅ 校验失败，终止后续代码
    }
    const res = await updatePhone({
      phoneNumber: form.newPhone,
    })

    if (res.code === 0) {
      await useUserStore().getUserInfo()
      uni.showToast({
        title: '手机号修改成功',
      })
      // 验证后 退出需要重新登录
      setTimeout(() => {
        store.logout().then(() => {
          uni.reLaunch({ url: '/pages/login/index' })
        })
      }, 1500)
    }
  } catch (error) {
    console.log('修改手机号失败', error)
    uni.showToast({
      title: '手机号修改失败',
      icon: 'none',
    })
  } finally {
    submitting.value = false
  }
}
</script>

<style lang="scss" scoped>
.form-box ::v-deep .wd-input.is-cell {
  padding: 20px 0 !important;
}

.container {
  min-height: 100vh;
  background: #f8f8f8;
}

.form-box {
  background: #fff;
  padding: 40rpx;
  margin: 40rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.tip-text {
  color: #666;
  font-size: 28rpx;
  margin-bottom: 40rpx;
}

.current-phone {
  color: #333;
  font-size: 32rpx;
  margin-bottom: 60rpx;
}

.mt-40 {
  margin-top: 40rpx;
}

// 响应式适配
@media (max-width: 375px) {
  .form-box {
    padding: 30rpx;
    margin: 30rpx;
  }

  .tip-text {
    font-size: 26rpx;
  }

  .current-phone {
    font-size: 30rpx;
  }
}
</style>
